package com.googlecode.wmbruby;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;

import org.apache.bsf.BSFException;
import org.apache.bsf.BSFManager;


public class RubyMap {

	private static final String WRAPPER_SCRIPT = 
	    "require 'Element'\n" +
		"inRoot = Element.new $javaIn\n" +
		"outRoot = Element.new($javaOut, true)\n";
	
	private String script;
	
	public RubyMap(Reader script) throws IOException {
		this.script = wrapScript(script);
		
		String language = "ruby";
		String engineName = "org.jruby.javasupport.bsf.JRubyEngine";
		String[] extensions = {"rb"};
		BSFManager.registerScriptingEngine(language, engineName, extensions);
	}
	
	private String wrapScript(Reader scriptToWrap) throws IOException {
		StringBuffer scriptToExec = new StringBuffer();
		scriptToExec.append(WRAPPER_SCRIPT);
		BufferedReader br = new BufferedReader(scriptToWrap);
		String line = br.readLine();
		
		while(line != null) {
			scriptToExec.append(line);
			scriptToExec.append('\n');
			
			line = br.readLine();
		}
		
		return scriptToExec.toString();
	}

	public void map(MbElement in, MbElement out) throws BSFException, IOException {
		BSFManager manager = new BSFManager();

		manager.declareBean("javaIn", in, MbElement.class);
		manager.declareBean("javaOut", out, MbElement.class);
		
		//System.out.println(scriptToExec.toString());
		try {
			manager.exec("ruby", "java", 1, 1, script);
		} catch(BSFException e) {
			e.printStackTrace();
			throw e;
		}
			
	}

}
